package com.ywx.yypicturebackend.manager.upload;

import cn.hutool.core.io.FileUtil;
import com.ywx.yypicturebackend.constant.FileConstant;
import com.ywx.yypicturebackend.exception.ErrorCode;
import com.ywx.yypicturebackend.exception.ThrowUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@Service
public class FilePictureUpload extends PictureUploadTemplate{
    @Override
    protected void processFile(Object inputSource, File file) throws IOException {
        MultipartFile multipartFile = (MultipartFile) inputSource;

        multipartFile.transferTo(file);
    }

    @Override
    protected String getOriginalFilename(Object inputSource) {
        MultipartFile multipartFile = (MultipartFile) inputSource;
       return multipartFile.getOriginalFilename();
    }

    @Override
    protected void validPicture(Object inputSource) {
        MultipartFile multipartFile = (MultipartFile) inputSource;
        ThrowUtils.throwIf(multipartFile == null, ErrorCode.PARAMS_ERROR);

        //校验图片的大小
        long fileSize = multipartFile.getSize();//单位为字节
        ThrowUtils.throwIf(fileSize > FileConstant.MAX_FILE_SIZE * FileConstant.ONE_M,
                ErrorCode.PARAMS_ERROR, String.format("文件大小不能超过%s%s", FileConstant.MAX_FILE_SIZE, "MB"));

        //校验图片后缀是否合法
        String originalFilename = multipartFile.getOriginalFilename();//获取文件原始名字
        ThrowUtils.throwIf(!FileConstant.ALLOW_FORMAT_LIST.contains(FileUtil.getSuffix(originalFilename)), ErrorCode.PARAMS_ERROR, "文件类型错误");
    }
}
